package mianshi;

import entity.User;
import sun.misc.Unsafe;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @author MaoLin Wang
 * @description
 * @date 2020/9/1 8:36 上午
 */
public class UnSafeTest {
    public static void main(String[] args) throws InstantiationException, NoSuchFieldException {
        Unsafe unsafe = getUnsafe();
        User user = (User) unsafe.allocateInstance(User.class);
        System.out.println(user);

        Field ageFiled = User.class.getDeclaredField("age");
        unsafe.putInt(user,unsafe.objectFieldOffset(ageFiled),10);
        System.out.println(user.getAge());

        User serial = serial(user);
        System.out.println(serial.getAge());
    }

    public static User forname(){
        Class<?> user = null;
        try {
            user = Class.forName("User");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            assert user != null;
            return (User) user.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static User newInstance(){
        try {
            return User.class.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static User construct(){
        try {
            return User.class.getConstructor().newInstance();
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static User clone2(User user){
        if (user!=null){
            try {
                return (User) user.clone();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public static User serial(User user){
        try {
            ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("/Users/wangmaolin/Documents/user.txt"));
            oos.writeObject(user);
            oos.close();;

            ObjectInputStream ois=new ObjectInputStream(new FileInputStream("/Users/wangmaolin/Documents/user.txt"));
            User user1 = (User) ois.readObject();
            return user1;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Unsafe getUnsafe(){
        try {
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            return (Unsafe) theUnsafe.get(null);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return  null;
    }
}
